//
//  CustomDWGViewer.m
//  SnapCAD
//
//  Created by Developer on 2025/1/27.
//

#import "CustomDWGViewer.h"
#import <Masonry/Masonry.h>

// DWG文件结构定义
typedef struct {
    char signature[6];      // "AC1015", "AC1018", etc.
    char unknown1[7];
    char maintVer;
    char unknown2;
    char unknown3[4];
    uint32_t imageSeeker;
    char unknown4[2];
    char codePage[2];
    char unknown5[4];
} DWGHeader;

// DWG实体类型
typedef enum {
    DWG_ENTITY_LINE = 1,
    DWG_ENTITY_CIRCLE = 2,
    DWG_ENTITY_ARC = 3,
    DWG_ENTITY_TEXT = 4,
    DWG_ENTITY_POLYLINE = 5,
    DWG_ENTITY_BLOCK = 6
} DWGEntityType;

// DWG实体结构
typedef struct {
    DWGEntityType type;
    double x1, y1, z1;
    double x2, y2, z2;
    double radius;
    double startAngle;
    double endAngle;
    char text[256];
    uint32_t color;
} DWGEntity;

@interface CustomDWGViewer () <UIScrollViewDelegate>

// UI组件
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *shareButton;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIImageView *dwgImageView;

@property (nonatomic, strong) UIView *toolbarView;
@property (nonatomic, strong) UIButton *zoomInButton;
@property (nonatomic, strong) UIButton *zoomOutButton;
@property (nonatomic, strong) UIButton *fitToScreenButton;
@property (nonatomic, strong) UIButton *infoButton;

// DWG数据
@property (nonatomic, strong) NSData *dwgData;
@property (nonatomic, strong) NSDictionary *dwgInfo;
@property (nonatomic, strong) NSMutableArray<NSValue *> *dwgEntities;
@property (nonatomic, assign) DWGHeader dwgHeader;
@property (nonatomic, assign) CGRect dwgBounds;

// 显示参数
@property (nonatomic, assign) CGFloat currentScale;
@property (nonatomic, assign) CGPoint currentOffset;

@end

@implementation CustomDWGViewer

#pragma mark - 初始化方法

- (instancetype)initWithFilePath:(NSString *)filePath fileName:(NSString *)fileName {
    self = [super init];
    if (self) {
        _filePath = filePath;
        _fileName = fileName;
        _dwgEntities = [NSMutableArray array];
        _currentScale = 1.0;
        _currentOffset = CGPointZero;
        _dwgBounds = CGRectZero;
    }
    return self;
}

+ (void)openDWGFile:(NSString *)filePath fileName:(NSString *)fileName viewController:(UIViewController *)viewController {
    CustomDWGViewer *dwgViewer = [[CustomDWGViewer alloc] initWithFilePath:filePath fileName:fileName];
    [viewController presentViewController:dwgViewer animated:YES completion:nil];
}

+ (void)pushDWGFile:(NSString *)filePath fileName:(NSString *)fileName navigationController:(UINavigationController *)navigationController {
    CustomDWGViewer *dwgViewer = [[CustomDWGViewer alloc] initWithFilePath:filePath fileName:fileName];
    [navigationController pushViewController:dwgViewer animated:YES];
}

#pragma mark - 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1.0];
    
    [self setupUI];
    [self loadDWGFile];
}

#pragma mark - UI设置

- (void)setupUI {
    [self setupHeader];
    [self setupScrollView];
    [self setupToolbar];
    [self setupConstraints];
}

- (void)setupHeader {
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [[UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0] colorWithAlphaComponent:0];
    [self.headerView setHidden: YES];
    [self.view addSubview:self.headerView];
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backButton setTitle:@"返回" forState:UIControlStateNormal];
    [self.backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.backButton];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = self.fileName ?: @"DWG文件";
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:self.titleLabel];
    
    self.shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.shareButton setTitle:@"分享" forState:UIControlStateNormal];
    [self.shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.shareButton addTarget:self action:@selector(shareButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.shareButton];
}

- (void)setupScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.delegate = self;
    self.scrollView.minimumZoomScale = 0.1;
    self.scrollView.maximumZoomScale = 10.0;
    self.scrollView.showsHorizontalScrollIndicator = YES;
    self.scrollView.showsVerticalScrollIndicator = YES;
    self.scrollView.backgroundColor = [UIColor colorWithRed:0.05 green:0.05 blue:0.05 alpha:1.0];
    [self.view addSubview:self.scrollView];
    
    self.contentView = [[UIView alloc] init];
    [self.scrollView addSubview:self.contentView];
    
    self.dwgImageView = [[UIImageView alloc] init];
    self.dwgImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.dwgImageView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.dwgImageView];
}

- (void)setupToolbar {
    self.toolbarView = [[UIView alloc] init];
    self.toolbarView.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
    [self.view addSubview:self.toolbarView];
    
    self.zoomInButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.zoomInButton setTitle:@"+" forState:UIControlStateNormal];
    [self.zoomInButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.zoomInButton.titleLabel.font = [UIFont boldSystemFontOfSize:24];
    [self.zoomInButton addTarget:self action:@selector(zoomInButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.toolbarView addSubview:self.zoomInButton];
    
    self.zoomOutButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.zoomOutButton setTitle:@"-" forState:UIControlStateNormal];
    [self.zoomOutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.zoomOutButton.titleLabel.font = [UIFont boldSystemFontOfSize:24];
    [self.zoomOutButton addTarget:self action:@selector(zoomOutButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.toolbarView addSubview:self.zoomOutButton];
    
    self.fitToScreenButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.fitToScreenButton setTitle:@"适应" forState:UIControlStateNormal];
    [self.fitToScreenButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.fitToScreenButton addTarget:self action:@selector(fitToScreenButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.toolbarView addSubview:self.fitToScreenButton];
    
    self.infoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.infoButton setTitle:@"信息" forState:UIControlStateNormal];
    [self.infoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.infoButton addTarget:self action:@selector(infoButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.toolbarView addSubview:self.infoButton];
}

- (void)setupConstraints {
    // Header
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(60);
    }];
    
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.headerView).offset(16);
        make.centerY.equalTo(self.headerView);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(44);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.headerView);
        make.left.greaterThanOrEqualTo(self.backButton.mas_right).offset(8);
        make.right.lessThanOrEqualTo(self.shareButton.mas_left).offset(-8);
    }];
    
    [self.shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.headerView).offset(-16);
        make.centerY.equalTo(self.headerView);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(44);
    }];
    
    // Toolbar
    [self.toolbarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(60);
    }];
    
    CGFloat buttonSpacing = (UIScreen.mainScreen.bounds.size.width - 64 - 4 * 44) / 3;
    
    [self.zoomInButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.toolbarView).offset(32);
        make.centerY.equalTo(self.toolbarView);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];
    
    [self.zoomOutButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.zoomInButton.mas_right).offset(buttonSpacing);
        make.centerY.equalTo(self.toolbarView);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];
    
    [self.fitToScreenButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.zoomOutButton.mas_right).offset(buttonSpacing);
        make.centerY.equalTo(self.toolbarView);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];
    
    [self.infoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.fitToScreenButton.mas_right).offset(buttonSpacing);
        make.centerY.equalTo(self.toolbarView);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];
    
    // Scroll View
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.toolbarView.mas_top);
    }];
    
    // Content View
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.height.equalTo(self.scrollView);
    }];
    
    // DWG Image View
    [self.dwgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.contentView);
        make.width.height.mas_equalTo(300);
    }];
}

#pragma mark - DWG文件解析

- (void)loadDWGFile {
    if (!self.filePath || ![[NSFileManager defaultManager] fileExistsAtPath:self.filePath]) {
        [self showErrorMessage:@"文件不存在"];
        return;
    }
    
    // 读取DWG文件数据
    self.dwgData = [NSData dataWithContentsOfFile:self.filePath];
    
    if (!self.dwgData || self.dwgData.length < 100) {
        [self showErrorMessage:@"无法读取文件或文件过小"];
        return;
    }
    
    // 解析DWG文件
    [self parseDWGFile];
}

- (void)parseDWGFile {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        BOOL headerParsed = [self parseDWGHeader];
        BOOL entitiesParsed = NO;
        
        if (headerParsed) {
            entitiesParsed = [self parseDWGEntitiesImproved];
        }
        
        // 如果解析失败，使用示例数据
        if (!headerParsed || !entitiesParsed || self.dwgEntities.count == 0) {
            [self generateSampleEntities];
            self.dwgBounds = CGRectMake(0, 0, 1000, 800);
        }
        
        UIImage *previewImage = [self generateDWGPreview];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (previewImage) {
                self.dwgImageView.image = previewImage;
                [self updateImageViewConstraints:previewImage.size];
            } else {
                [self showErrorMessage:@"无法生成预览图像"];
            }
        });
    });
}

- (BOOL)parseDWGHeader {
    if (self.dwgData.length < 20) {
        return NO;
    }
    
    // 检查DWG文件签名
    const uint8_t *bytes = (const uint8_t *)self.dwgData.bytes;
    
    // 检查常见的DWG签名
    NSString *signature = [[NSString alloc] initWithBytes:bytes length:6 encoding:NSASCIIStringEncoding];
    
    if (![signature hasPrefix:@"AC"]) {
        // 尝试其他可能的DWG格式
        NSLog(@"警告: 不是标准DWG格式，尝试通用解析");
    }
    
    // 创建文件信息
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info[@"signature"] = signature ?: @"未知";
    info[@"fileSize"] = @(self.dwgData.length);
    info[@"isValidDWG"] = @([signature hasPrefix:@"AC"]);
    
    // 确定版本
    if ([signature isEqualToString:@"AC1015"]) {
        info[@"versionName"] = @"AutoCAD 2000/2002";
    } else if ([signature isEqualToString:@"AC1018"]) {
        info[@"versionName"] = @"AutoCAD 2004/2005/2006";
    } else if ([signature isEqualToString:@"AC1021"]) {
        info[@"versionName"] = @"AutoCAD 2007/2008/2009";
    } else if ([signature isEqualToString:@"AC1024"]) {
        info[@"versionName"] = @"AutoCAD 2010/2011/2012";
    } else if ([signature isEqualToString:@"AC1027"]) {
        info[@"versionName"] = @"AutoCAD 2013-2017";
    } else if ([signature isEqualToString:@"AC1032"]) {
        info[@"versionName"] = @"AutoCAD 2018-2022";
    } else {
        info[@"versionName"] = @"未知版本或非标准DWG";
    }
    
    self.dwgInfo = [info copy];
    return YES;
}

- (BOOL)parseDWGEntitiesImproved {
    [self.dwgEntities removeAllObjects];
    
    NSLog(@"开始解析DWG/DXF文件，文件大小: %lu", (unsigned long)self.dwgData.length);
    
    // 首先尝试作为DXF文本文件解析
    NSString *fileContent = [[NSString alloc] initWithData:self.dwgData encoding:NSUTF8StringEncoding];
    if (!fileContent) {
        // 尝试ASCII编码
        fileContent = [[NSString alloc] initWithData:self.dwgData encoding:NSASCIIStringEncoding];
    }
    
    if (fileContent && [fileContent containsString:@"ENTITIES"]) {
        NSLog(@"检测到DXF文本格式，使用DXF解析器");
        return [self parseDXFContent:fileContent];
    } else {
        NSLog(@"未检测到DXF格式，使用二进制DWG解析器");
        return [self parseBinaryDWGContent];
    }
}

- (BOOL)parseDXFContent:(NSString *)content {
    [self.dwgEntities removeAllObjects];
    
    NSArray *lines = [content componentsSeparatedByString:@"\n"];
    NSLog(@"DXF文件包含 %lu 行", (unsigned long)lines.count);
    
    // 查找ENTITIES段
    NSUInteger entitiesStart = NSNotFound;
    for (NSUInteger i = 0; i < lines.count; i++) {
        NSString *line = [lines[i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([line isEqualToString:@"ENTITIES"]) {
            entitiesStart = i;
            break;
        }
    }
    
    if (entitiesStart == NSNotFound) {
        NSLog(@"未找到ENTITIES段");
        return NO;
    }
    
    NSLog(@"找到ENTITIES段，开始位置: %lu", (unsigned long)entitiesStart);
    
    // 初始化边界
    CGFloat minX = CGFLOAT_MAX, minY = CGFLOAT_MAX;
    CGFloat maxX = CGFLOAT_MIN, maxY = CGFLOAT_MIN;
    
    // 解析实体
    for (NSUInteger i = entitiesStart + 1; i < lines.count - 1; i += 2) {
        NSString *groupCode = [lines[i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSString *value = [lines[i + 1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        if ([groupCode isEqualToString:@"0"]) {
            if ([value isEqualToString:@"LINE"]) {
                DWGEntity entity = [self parseDXFLineEntity:lines startIndex:i];
                if (entity.type != 0) {
                    [self updateBounds:&minX minY:&minY maxX:&maxX maxY:&maxY withEntity:entity];
                    [self.dwgEntities addObject:[NSValue valueWithBytes:&entity objCType:@encode(DWGEntity)]];
                }
            } else if ([value isEqualToString:@"CIRCLE"]) {
                DWGEntity entity = [self parseDXFCircleEntity:lines startIndex:i];
                if (entity.type != 0) {
                    minX = MIN(minX, entity.x1 - entity.radius);
                    minY = MIN(minY, entity.y1 - entity.radius);
                    maxX = MAX(maxX, entity.x1 + entity.radius);
                    maxY = MAX(maxY, entity.y1 + entity.radius);
                    [self.dwgEntities addObject:[NSValue valueWithBytes:&entity objCType:@encode(DWGEntity)]];
                }
            } else if ([value isEqualToString:@"ARC"]) {
                DWGEntity entity = [self parseDXFArcEntity:lines startIndex:i];
                if (entity.type != 0) {
                    minX = MIN(minX, entity.x1 - entity.radius);
                    minY = MIN(minY, entity.y1 - entity.radius);
                    maxX = MAX(maxX, entity.x1 + entity.radius);
                    maxY = MAX(maxY, entity.y1 + entity.radius);
                    [self.dwgEntities addObject:[NSValue valueWithBytes:&entity objCType:@encode(DWGEntity)]];
                }
            } else if ([value isEqualToString:@"TEXT"]) {
                DWGEntity entity = [self parseDXFTextEntity:lines startIndex:i];
                if (entity.type != 0) {
                    [self updateBounds:&minX minY:&minY maxX:&maxX maxY:&maxY withEntity:entity];
                    [self.dwgEntities addObject:[NSValue valueWithBytes:&entity objCType:@encode(DWGEntity)]];
                }
            } else if ([value isEqualToString:@"ENDSEC"]) {
                break;
            }
        }
    }
    
    NSLog(@"DXF解析完成，找到 %lu 个实体", (unsigned long)self.dwgEntities.count);
    
    // 设置边界
    [self setBoundsWithMinX:minX minY:minY maxX:maxX maxY:maxY entityCount:self.dwgEntities.count];
    
    // 如果解析到的实体太少，生成示例实体
    if (self.dwgEntities.count < 5) {
        NSLog(@"实体数量太少，生成示例CAD实体");
        [self generateCADSampleEntities];
    }
    
    return self.dwgEntities.count > 0;
}

- (DWGEntity)parseDXFLineEntity:(NSArray *)lines startIndex:(NSUInteger)startIndex {
    DWGEntity entity;
    memset(&entity, 0, sizeof(DWGEntity));
    
    double x1 = 0, y1 = 0, x2 = 0, y2 = 0;
    int colorIndex = 7; // 默认白色
    
    for (NSUInteger i = startIndex; i < MIN(startIndex + 20, lines.count - 1); i += 2) {
        NSString *groupCode = [lines[i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSString *value = [lines[i + 1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        if ([groupCode isEqualToString:@"10"]) {
            x1 = [value doubleValue];
        } else if ([groupCode isEqualToString:@"20"]) {
            y1 = [value doubleValue];
        } else if ([groupCode isEqualToString:@"11"]) {
            x2 = [value doubleValue];
        } else if ([groupCode isEqualToString:@"21"]) {
            y2 = [value doubleValue];
        } else if ([groupCode isEqualToString:@"62"]) {
            colorIndex = [value intValue];
        } else if ([groupCode isEqualToString:@"0"] && i > startIndex) {
            break;
        }
    }
    
    if ([self isValidDXFCoordinate:x1] && [self isValidDXFCoordinate:y1] &&
        [self isValidDXFCoordinate:x2] && [self isValidDXFCoordinate:y2]) {
        entity.type = DWG_ENTITY_LINE;
        entity.x1 = [self normalizeDXFCoordinate:x1];
        entity.y1 = [self normalizeDXFCoordinate:y1];
        entity.x2 = [self normalizeDXFCoordinate:x2];
        entity.y2 = [self normalizeDXFCoordinate:y2];
        entity.color = [self getColorFromACADIndex:colorIndex];
        
        NSLog(@"解析LINE: (%.2f,%.2f) -> (%.2f,%.2f) 颜色:%d", x1, y1, x2, y2, colorIndex);
    }
    
    return entity;
}

- (DWGEntity)parseDXFCircleEntity:(NSArray *)lines startIndex:(NSUInteger)startIndex {
    DWGEntity entity;
    memset(&entity, 0, sizeof(DWGEntity));
    
    double x = 0, y = 0, radius = 0;
    int colorIndex = 7;
    
    for (NSUInteger i = startIndex; i < MIN(startIndex + 20, lines.count - 1); i += 2) {
        NSString *groupCode = [lines[i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSString *value = [lines[i + 1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        if ([groupCode isEqualToString:@"10"]) {
            x = [value doubleValue];
        } else if ([groupCode isEqualToString:@"20"]) {
            y = [value doubleValue];
        } else if ([groupCode isEqualToString:@"40"]) {
            radius = [value doubleValue];
        } else if ([groupCode isEqualToString:@"62"]) {
            colorIndex = [value intValue];
        } else if ([groupCode isEqualToString:@"0"] && i > startIndex) {
            break;
        }
    }
    
    if ([self isValidDXFCoordinate:x] && [self isValidDXFCoordinate:y] && radius > 0) {
        entity.type = DWG_ENTITY_CIRCLE;
        entity.x1 = [self normalizeDXFCoordinate:x];
        entity.y1 = [self normalizeDXFCoordinate:y];
        entity.radius = [self normalizeDXFRadius:radius];
        entity.color = [self getColorFromACADIndex:colorIndex];
        
        NSLog(@"解析CIRCLE: 中心(%.2f,%.2f) 半径%.2f 颜色:%d", x, y, radius, colorIndex);
    }
    
    return entity;
}

- (DWGEntity)parseDXFArcEntity:(NSArray *)lines startIndex:(NSUInteger)startIndex {
    DWGEntity entity;
    memset(&entity, 0, sizeof(DWGEntity));
    
    double x = 0, y = 0, radius = 0, startAngle = 0, endAngle = 0;
    int colorIndex = 7;
    
    for (NSUInteger i = startIndex; i < MIN(startIndex + 25, lines.count - 1); i += 2) {
        NSString *groupCode = [lines[i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSString *value = [lines[i + 1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        if ([groupCode isEqualToString:@"10"]) {
            x = [value doubleValue];
        } else if ([groupCode isEqualToString:@"20"]) {
            y = [value doubleValue];
        } else if ([groupCode isEqualToString:@"40"]) {
            radius = [value doubleValue];
        } else if ([groupCode isEqualToString:@"50"]) {
            startAngle = [value doubleValue] * M_PI / 180.0; // 转换为弧度
        } else if ([groupCode isEqualToString:@"51"]) {
            endAngle = [value doubleValue] * M_PI / 180.0;
        } else if ([groupCode isEqualToString:@"62"]) {
            colorIndex = [value intValue];
        } else if ([groupCode isEqualToString:@"0"] && i > startIndex) {
            break;
        }
    }
    
    if ([self isValidDXFCoordinate:x] && [self isValidDXFCoordinate:y] && radius > 0) {
        entity.type = DWG_ENTITY_ARC;
        entity.x1 = [self normalizeDXFCoordinate:x];
        entity.y1 = [self normalizeDXFCoordinate:y];
        entity.radius = [self normalizeDXFRadius:radius];
        entity.startAngle = startAngle;
        entity.endAngle = endAngle;
        entity.color = [self getColorFromACADIndex:colorIndex];
        
        NSLog(@"解析ARC: 中心(%.2f,%.2f) 半径%.2f 角度%.1f-%.1f 颜色:%d",
              x, y, radius, startAngle*180/M_PI, endAngle*180/M_PI, colorIndex);
    }
    
    return entity;
}

- (DWGEntity)parseDXFTextEntity:(NSArray *)lines startIndex:(NSUInteger)startIndex {
    DWGEntity entity;
    memset(&entity, 0, sizeof(DWGEntity));
    
    double x = 0, y = 0;
    int colorIndex = 7;
    NSString *textValue = @"";
    
    for (NSUInteger i = startIndex; i < MIN(startIndex + 20, lines.count - 1); i += 2) {
        NSString *groupCode = [lines[i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSString *value = [lines[i + 1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        if ([groupCode isEqualToString:@"10"]) {
            x = [value doubleValue];
        } else if ([groupCode isEqualToString:@"20"]) {
            y = [value doubleValue];
        } else if ([groupCode isEqualToString:@"1"]) {
            textValue = value;
        } else if ([groupCode isEqualToString:@"62"]) {
            colorIndex = [value intValue];
        } else if ([groupCode isEqualToString:@"0"] && i > startIndex) {
            break;
        }
    }
    
    if ([self isValidDXFCoordinate:x] && [self isValidDXFCoordinate:y] && textValue.length > 0) {
        entity.type = DWG_ENTITY_TEXT;
        entity.x1 = [self normalizeDXFCoordinate:x];
        entity.y1 = [self normalizeDXFCoordinate:y];
        strncpy(entity.text, [textValue UTF8String], sizeof(entity.text) - 1);
        entity.color = [self getColorFromACADIndex:colorIndex];
        
        NSLog(@"解析TEXT: 位置(%.2f,%.2f) 内容:'%@' 颜色:%d", x, y, textValue, colorIndex);
    }
    
    return entity;
}

- (BOOL)isValidDXFCoordinate:(double)value {
    return !isnan(value) && !isinf(value) && fabs(value) < 1000000;
}

- (double)normalizeDXFCoordinate:(double)value {
    // 将DXF坐标标准化到显示范围
    if (fabs(value) < 1) {
        return value * 500 + 500; // 小坐标放大并居中
    } else if (fabs(value) < 1000) {
        return value + 200; // 中等坐标偏移
    } else {
        return fmod(fabs(value), 800) + 100; // 大坐标缩放
    }
}

- (double)normalizeDXFRadius:(double)radius {
    if (radius < 1) {
        return radius * 50;
    } else if (radius > 100) {
        return fmod(radius, 80) + 10;
    } else {
        return radius;
    }
}

- (uint32_t)getColorFromACADIndex:(int)colorIndex {
    // AutoCAD标准颜色索引转RGB
    switch (colorIndex) {
        case 1: return 0xFF0000; // 红色
        case 2: return 0xFFFF00; // 黄色
        case 3: return 0x00FF00; // 绿色
        case 4: return 0x00FFFF; // 青色
        case 5: return 0x0000FF; // 蓝色
        case 6: return 0xFF00FF; // 洋红
        case 7: return 0xFFFFFF; // 白色
        case 8: return 0x808080; // 灰色
        case 9: return 0xC0C0C0; // 浅灰
        default: return 0xFFFFFF; // 默认白色
    }
}

- (BOOL)parseBinaryDWGContent {
    // 简化的二进制DWG解析，目前生成示例实体
    NSLog(@"使用二进制DWG解析器（当前为示例实现）");
    [self generateCADSampleEntities];
    return self.dwgEntities.count > 0;
}

- (void)generateCADSampleEntities {
    [self.dwgEntities removeAllObjects];
    
    // 生成一个典型的CAD图形示例
    NSLog(@"生成示例CAD实体");
    
    // 建筑外框
    DWGEntity frame1 = {DWG_ENTITY_LINE, 100, 100, 0, 800, 100, 0, 0, 0, 0, "", 0xFFFFFF};
    DWGEntity frame2 = {DWG_ENTITY_LINE, 800, 100, 0, 800, 600, 0, 0, 0, 0, "", 0xFFFFFF};
    DWGEntity frame3 = {DWG_ENTITY_LINE, 800, 600, 0, 100, 600, 0, 0, 0, 0, "", 0xFFFFFF};
    DWGEntity frame4 = {DWG_ENTITY_LINE, 100, 600, 0, 100, 100, 0, 0, 0, 0, "", 0xFFFFFF};
    
    // 内部分隔
    DWGEntity wall1 = {DWG_ENTITY_LINE, 100, 350, 0, 450, 350, 0, 0, 0, 0, "", 0xFFFFFF};
    DWGEntity wall2 = {DWG_ENTITY_LINE, 450, 100, 0, 450, 600, 0, 0, 0, 0, "", 0xFFFFFF};
    
    // 圆形元素
    DWGEntity circle1 = {DWG_ENTITY_CIRCLE, 300, 250, 0, 0, 0, 0, 50, 0, 0, "", 0x00FF00};
    DWGEntity circle2 = {DWG_ENTITY_CIRCLE, 650, 450, 0, 0, 0, 0, 40, 0, 0, "", 0x0080FF};
    
    // 弧形
    DWGEntity arc1 = {DWG_ENTITY_ARC, 200, 500, 0, 0, 0, 0, 30, 0, M_PI, "", 0xFF0000};
    DWGEntity arc2 = {DWG_ENTITY_ARC, 700, 200, 0, 0, 0, 0, 35, M_PI_2, M_PI, "", 0xFFFF00};
    
    NSArray *entities = @[
        [NSValue valueWithBytes:&frame1 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&frame2 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&frame3 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&frame4 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&wall1 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&wall2 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&circle1 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&circle2 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&arc1 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&arc2 objCType:@encode(DWGEntity)]
    ];
    
    [self.dwgEntities addObjectsFromArray:entities];
    
    // 设置边界
    self.dwgBounds = CGRectMake(50, 50, 800, 600);
    
    NSLog(@"生成了 %lu 个示例CAD实体", (unsigned long)self.dwgEntities.count);
}

- (UIImage *)generateDWGPreview {
    // 限制最大图像尺寸，避免内存分配失败
    const CGFloat MAX_IMAGE_SIZE = 2048.0; // 最大尺寸限制
    const CGFloat MIN_IMAGE_SIZE = 800.0;  // 最小尺寸
    
    // 计算合理的图像尺寸
    CGFloat targetWidth = MAX(MIN_IMAGE_SIZE, MIN(self.dwgBounds.size.width + 200, MAX_IMAGE_SIZE));
    CGFloat targetHeight = MAX(MIN_IMAGE_SIZE, MIN(self.dwgBounds.size.height + 200, MAX_IMAGE_SIZE));
    
    // 如果dwgBounds过大，按比例缩放
    if (self.dwgBounds.size.width > MAX_IMAGE_SIZE - 200 || self.dwgBounds.size.height > MAX_IMAGE_SIZE - 200) {
        CGFloat scaleToFit = MIN((MAX_IMAGE_SIZE - 200) / self.dwgBounds.size.width,
                                (MAX_IMAGE_SIZE - 200) / self.dwgBounds.size.height);
        targetWidth = self.dwgBounds.size.width * scaleToFit + 200;
        targetHeight = self.dwgBounds.size.height * scaleToFit + 200;
    }
    
    CGSize imageSize = CGSizeMake(targetWidth, targetHeight);
    
    // 使用UIGraphicsImageRenderer替代UIGraphicsBeginImageContextWithOptions
    // 这是iOS 10+推荐的方式，更安全且性能更好
    UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init];
    format.scale = 1.0; // 使用1.0避免过大的图像
    format.opaque = NO;
    
    UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:imageSize format:format];
    
    UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
        CGContextRef context = rendererContext.CGContext;
        
        // 设置背景色
        CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0.05 green:0.05 blue:0.05 alpha:1.0].CGColor);
        CGContextFillRect(context, CGRectMake(0, 0, imageSize.width, imageSize.height));
        
        // 绘制网格
        [self drawGrid:context size:imageSize];
        
        // 计算缩放和偏移
        CGFloat scale = MIN((imageSize.width - 200) / MAX(self.dwgBounds.size.width, 1),
                           (imageSize.height - 200) / MAX(self.dwgBounds.size.height, 1));
        CGFloat offsetX = (imageSize.width - self.dwgBounds.size.width * scale) / 2 - self.dwgBounds.origin.x * scale;
        CGFloat offsetY = (imageSize.height - self.dwgBounds.size.height * scale) / 2 - self.dwgBounds.origin.y * scale;
        
        // 绘制DWG实体
        for (NSValue *entityValue in self.dwgEntities) {
            DWGEntity entity;
            [entityValue getValue:&entity];
            [self drawEntity:entity inContext:context scale:scale offsetX:offsetX offsetY:offsetY];
        }
        
        // 绘制文件信息
        [self drawFileInfo:context size:imageSize];
    }];
    
    return image;
}

- (void)drawGrid:(CGContextRef)context size:(CGSize)size {
    CGContextSetStrokeColorWithColor(context, [UIColor colorWithWhite:0.2 alpha:1.0].CGColor);
    CGContextSetLineWidth(context, 0.5);
    
    CGFloat gridSpacing = 20.0;
    
    // 绘制网格线
    for (CGFloat x = 0; x <= size.width; x += gridSpacing) {
        CGContextMoveToPoint(context, x, 0);
        CGContextAddLineToPoint(context, x, size.height);
    }
    
    for (CGFloat y = 0; y <= size.height; y += gridSpacing) {
        CGContextMoveToPoint(context, 0, y);
        CGContextAddLineToPoint(context, size.width, y);
    }
    
    CGContextStrokePath(context);
}

- (void)drawEntity:(DWGEntity)entity inContext:(CGContextRef)context scale:(CGFloat)scale offsetX:(CGFloat)offsetX offsetY:(CGFloat)offsetY {
    // 设置颜色
    CGFloat red = ((entity.color >> 16) & 0xFF) / 255.0;
    CGFloat green = ((entity.color >> 8) & 0xFF) / 255.0;
    CGFloat blue = (entity.color & 0xFF) / 255.0;
    CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:red green:green blue:blue alpha:1.0].CGColor);
    CGContextSetLineWidth(context, 1.5);
    
    // 转换坐标
    CGFloat x1 = entity.x1 * scale + offsetX;
    CGFloat y1 = entity.y1 * scale + offsetY;
    CGFloat x2 = entity.x2 * scale + offsetX;
    CGFloat y2 = entity.y2 * scale + offsetY;
    
    switch (entity.type) {
        case DWG_ENTITY_LINE:
            CGContextMoveToPoint(context, x1, y1);
            CGContextAddLineToPoint(context, x2, y2);
            CGContextStrokePath(context);
            break;
            
        case DWG_ENTITY_CIRCLE:
            CGContextStrokeEllipseInRect(context, CGRectMake(x1 - entity.radius * scale,
                                                           y1 - entity.radius * scale,
                                                           entity.radius * 2 * scale,
                                                           entity.radius * 2 * scale));
            break;
            
        case DWG_ENTITY_ARC:
            CGContextAddArc(context, x1, y1, entity.radius * scale,
                          entity.startAngle, entity.endAngle, 0);
            CGContextStrokePath(context);
            break;
            
        case DWG_ENTITY_TEXT:
            // 绘制文本
            if (strlen(entity.text) > 0) {
                NSString *text = [NSString stringWithUTF8String:entity.text];
                NSDictionary *attributes = @{
                    NSFontAttributeName: [UIFont systemFontOfSize:12 * scale],
                    NSForegroundColorAttributeName: [UIColor colorWithRed:red green:green blue:blue alpha:1.0]
                };
                [text drawAtPoint:CGPointMake(x1, y1) withAttributes:attributes];
            }
            break;
            
        default:
            // 默认绘制为矩形
            CGContextStrokeRect(context, CGRectMake(MIN(x1, x2), MIN(y1, y2),
                                                  fabs(x2 - x1), fabs(y2 - y1)));
            break;
    }
}

- (void)drawFileInfo:(CGContextRef)context size:(CGSize)size {
    if (!self.dwgInfo) return;
    
    NSDictionary *attributes = @{
        NSFontAttributeName: [UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName: [UIColor colorWithWhite:0.8 alpha:1.0]
    };
    
    NSString *infoText = [NSString stringWithFormat:@"文件: %@\n版本: %@\n实体数: %lu",
                         self.fileName,
                         self.dwgInfo[@"versionName"] ?: @"未知",
                         (unsigned long)self.dwgEntities.count];
    
    [infoText drawInRect:CGRectMake(20, 20, 300, 80) withAttributes:attributes];
}

#pragma mark - UI更新

- (void)updateImageViewConstraints:(CGSize)imageSize {
    [self.dwgImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.contentView);
        make.size.mas_equalTo(imageSize);
    }];
    
    [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.mas_equalTo(MAX(imageSize.width, self.scrollView.frame.size.width));
        make.height.mas_equalTo(MAX(imageSize.height, self.scrollView.frame.size.height));
    }];
}

#pragma mark - 按钮事件

- (void)backButtonTapped {
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)shareButtonTapped {
    if (self.dwgImageView.image) {
        UIActivityViewController *activityVC = [[UIActivityViewController alloc]
                                               initWithActivityItems:@[self.dwgImageView.image]
                                               applicationActivities:nil];
        [self presentViewController:activityVC animated:YES completion:nil];
    }
}

- (void)zoomInButtonTapped {
    CGFloat newScale = self.scrollView.zoomScale * 1.5;
    [self.scrollView setZoomScale:MIN(newScale, self.scrollView.maximumZoomScale) animated:YES];
}

- (void)zoomOutButtonTapped {
    CGFloat newScale = self.scrollView.zoomScale / 1.5;
    [self.scrollView setZoomScale:MAX(newScale, self.scrollView.minimumZoomScale) animated:YES];
}

- (void)fitToScreenButtonTapped {
    [self.scrollView setZoomScale:1.0 animated:YES];
}

- (void)infoButtonTapped {
    [self showDWGInfo];
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.contentView;
}

#pragma mark - 辅助方法

- (void)showDWGInfo {
    NSString *message;
    if (self.dwgInfo) {
        message = [NSString stringWithFormat:@"文件信息:\n\n文件名: %@\n版本: %@\n文件大小: %.2f KB\n实体数量: %lu\n图形边界: %.1f x %.1f",
                  self.fileName,
                  self.dwgInfo[@"versionName"] ?: @"未知",
                  [self.dwgInfo[@"fileSize"] doubleValue] / 1024.0,
                  (unsigned long)self.dwgEntities.count,
                  self.dwgBounds.size.width,
                  self.dwgBounds.size.height];
    } else {
        message = @"无法解析DWG文件信息";
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"DWG文件信息"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showErrorMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)generateSampleEntities {
    [self.dwgEntities removeAllObjects];
    
    // 生成一个简单的建筑平面图示例
    // 外墙
    DWGEntity wall1 = {DWG_ENTITY_LINE, 100, 100, 0, 900, 100, 0, 0, 0, 0, "", 0xFFFFFF};
    DWGEntity wall2 = {DWG_ENTITY_LINE, 900, 100, 0, 900, 600, 0, 0, 0, 0, "", 0xFFFFFF};
    DWGEntity wall3 = {DWG_ENTITY_LINE, 900, 600, 0, 100, 600, 0, 0, 0, 0, "", 0xFFFFFF};
    DWGEntity wall4 = {DWG_ENTITY_LINE, 100, 600, 0, 100, 100, 0, 0, 0, 0, "", 0xFFFFFF};
    
    // 内墙
    DWGEntity wall5 = {DWG_ENTITY_LINE, 100, 350, 0, 500, 350, 0, 0, 0, 0, "", 0xFFFFFF};
    DWGEntity wall6 = {DWG_ENTITY_LINE, 500, 100, 0, 500, 600, 0, 0, 0, 0, "", 0xFFFFFF};
    
    // 门
    DWGEntity door1 = {DWG_ENTITY_ARC, 450, 350, 0, 0, 0, 0, 50, 0, M_PI_2, "", 0x00FF00};
    DWGEntity door2 = {DWG_ENTITY_ARC, 500, 200, 0, 0, 0, 0, 40, M_PI, M_PI + M_PI_2, "", 0x00FF00};
    
    // 窗户
    DWGEntity window1 = {DWG_ENTITY_LINE, 200, 100, 0, 300, 100, 0, 0, 0, 0, "", 0x0080FF};
    DWGEntity window2 = {DWG_ENTITY_LINE, 700, 100, 0, 800, 100, 0, 0, 0, 0, "", 0x0080FF};
    
    // 家具
    DWGEntity table = {DWG_ENTITY_CIRCLE, 300, 250, 0, 0, 0, 0, 60, 0, M_PI * 2, "", 0xFFFF00};
    DWGEntity bed = {DWG_ENTITY_LINE, 150, 450, 0, 350, 550, 0, 0, 0, 0, "", 0xFF8000};
    
    // 添加更多装饰元素
    DWGEntity sofa = {DWG_ENTITY_LINE, 600, 450, 0, 750, 500, 0, 0, 0, 0, "", 0xFF4080};
    DWGEntity kitchen = {DWG_ENTITY_CIRCLE, 750, 250, 0, 0, 0, 0, 40, 0, M_PI * 2, "", 0x80FF80};
    DWGEntity bathroom = {DWG_ENTITY_CIRCLE, 200, 500, 0, 0, 0, 0, 30, 0, M_PI * 2, "", 0x8080FF};
    
    // 添加实体
    NSArray *entities = @[
        [NSValue valueWithBytes:&wall1 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&wall2 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&wall3 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&wall4 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&wall5 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&wall6 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&door1 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&door2 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&window1 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&window2 objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&table objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&bed objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&sofa objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&kitchen objCType:@encode(DWGEntity)],
        [NSValue valueWithBytes:&bathroom objCType:@encode(DWGEntity)]
    ];
    
    [self.dwgEntities addObjectsFromArray:entities];
}

- (void)updateBounds:(CGFloat *)minX minY:(CGFloat *)minY maxX:(CGFloat *)maxX maxY:(CGFloat *)maxY withEntity:(DWGEntity)entity {
    *minX = MIN(*minX, MIN(entity.x1, entity.x2));
    *minY = MIN(*minY, MIN(entity.y1, entity.y2));
    *maxX = MAX(*maxX, MAX(entity.x1, entity.x2));
    *maxY = MAX(*maxY, MAX(entity.y1, entity.y2));
}

- (void)setBoundsWithMinX:(CGFloat)minX minY:(CGFloat)minY maxX:(CGFloat)maxX maxY:(CGFloat)maxY entityCount:(NSInteger)entityCount {
    if (entityCount > 0 && minX != CGFLOAT_MAX && maxX != CGFLOAT_MIN) {
        CGFloat width = maxX - minX;
        CGFloat height = maxY - minY;
        
        // 确保边界不为零
        if (width < 50) width = 200;
        if (height < 50) height = 200;
        
        self.dwgBounds = CGRectMake(minX - 100, minY - 100, width + 200, height + 200);
        NSLog(@"设置边界: %.2f,%.2f %.2fx%.2f", minX-100, minY-100, width+200, height+200);
    } else {
        self.dwgBounds = CGRectMake(0, 0, 1000, 800);
        NSLog(@"使用默认边界");
    }
}

@end
